package cn.vendsystem.com.consumer;


import cn.vendcommon.com.entity.constants.MQConstant;
import cn.vendsystem.com.service.InventoryService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;


@Slf4j
@Component
public class RollbackConsumer {

    @Autowired
    private InventoryService inventoryService;

    /**
     * 监听库存回滚队列
     * @param msg 消息体
     * @param channel 通道
     * @param tag 消息标签
     * @throws IOException IO异常
     */
    @RabbitListener(queues = MQConstant.ROLLBACK_QUEUE)
    public void handleRollback(Map<String, Object> msg, Channel channel,
                               @Header(AmqpHeaders.DELIVERY_TAG) long tag) throws IOException {
        try {
            Integer machineId = (Integer) msg.get("machineId");
            Map<String, Integer> intelligentMap = (Map<String, Integer>) msg.get("intelligentMap");

            // TODO 调用回滚逻辑,记录系统错误日志


            channel.basicAck(tag, false);
            log.info("库存回滚成功，machineId={}", machineId);
        } catch (Exception e) {
            log.error("库存回滚失败，msg={}", msg, e);
            // 如果回滚失败，可以选择人工介入或持久化到数据库
            channel.basicReject(tag, false);
        }
    }


}
